//
//  ViewController.m
//  BicycleMap
//
//  Created by vedon on 5/12/16.
//  Copyright © 2016 Qianqian. All rights reserved.
//
#define kMapViewDefaultZoomLevel 14
#define kMapViewContentXPadding 15
#define kBottomBarHeight 48

#import "ViewController.h"
#import "GSMapManager.h"
#import "PureLayout.h"
#import "GSToast.h"
#import "GSMapNavView.h"
#import "GSMapBottomBar.h"
#import "GSBottomButtonInfo.h"
#import "BMUserInfoViewController.h"
#import "BMUserManager.h"
#import "UIAlertView+BlocksKit.h"
#import "BMAnnotationView.h"
#import "BMPointAnnotation.h"
#import "BNRoutePlanModel.h"
#import "BNCoreServices.h"


@interface ViewController ()<BMKMapViewDelegate,GSMapManagerProtocol,GSMapNavViewDelegate,GSMapBottomBarDelegate,BNNaviUIManagerDelegate,BNNaviRoutePlanDelegate,BMAnnotationViewDelegate>
@property (nonatomic,strong) BMKMapView *mapView; //地图
@property (nonatomic,strong) GSMapNavView *navView; //导航按钮
@property (nonatomic,strong) GSMapBottomBar *bottomBar; // 底部按钮功能
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.mapView]; // 把地图加到屏幕上
    [self.mapView autoPinEdgesToSuperviewEdges]; //把地图的大小对应屏幕大小
    [self.mapView addSubview:self.bottomBar]; //把底部按钮加在地图上

    
    [self.bottomBar autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.mapView withOffset:-10];
    [self.bottomBar autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.mapView withOffset:kMapViewContentXPadding];
    [self.bottomBar autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.mapView withOffset:-kMapViewContentXPadding];
    [self.bottomBar autoSetDimension:ALDimensionHeight toSize:kBottomBarHeight];
    [self.bottomBar initialize];
    

    [self.mapView addSubview:self.navView];
    [self.navView autoSetDimensionsToSize:CGSizeMake([GSMapNavView buttinSize], 3*[GSMapNavView buttinSize]+10)];
    
    //导航按钮的底边对齐底部按钮的顶部，留出20 的间隙
    [self.navView autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.bottomBar withOffset:-20];
    
    //导航按钮的右边对齐底部按钮的右边
    [self.navView autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.bottomBar];
    
    [[GSMapManager shareManager] addObserver:self];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//视图出现之后，开始获取用户当前的位置76
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[GSMapManager shareManager] startLocateMyLocation];
}


#pragma mark - GSMapManagerProtocol

- (void)didGetUserCurrentLocation:(BMKUserLocation *)location
{
    //更新用户当前位置
    [self.mapView updateLocationData:location];
    
    //如果用户已经登录，则把用户当前位置上传到服务器
    if ([[BMUserManager shareManager] isLogin])
    {
        //把地理位置信息上传到云服务器
        [[BMUserManager shareManager] syncUserLocationToServer:location.location.coordinate];
    }
    
}

- (void)didFailToGetUserLocation
{
    //弹框提示用户定位失败
    [GSToast showToastWithText:@"定位失败" inView:self.view];
}


- (void)startRouteTo:(CLLocationCoordinate2D)endCoor
{
    

    if ([self checkServicesInited])
    {
        NSMutableArray *nodesArray = [[NSMutableArray alloc]initWithCapacity:2];
        CLLocationCoordinate2D startCoor = [GSMapManager shareManager].userLocation.location.coordinate;
        //起点 传入的是原始的经纬度坐标，若使用的是百度地图坐标，可以使用BNTools类进行坐标转化
        BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
        startNode.pos = [[BNPosition alloc] init];
        startNode.pos.x = startCoor.longitude;
        startNode.pos.y = startCoor.latitude;
        startNode.pos.eType = BNCoordinate_BaiduMapSDK;
        [nodesArray addObject:startNode];
        
        
        BNRoutePlanNode *midNode = [[BNRoutePlanNode alloc] init];
        midNode.pos = [[BNPosition alloc] init];
        midNode.pos.x = endCoor.longitude;
        midNode.pos.y = endCoor.latitude;
        midNode.pos.eType = BNCoordinate_BaiduMapSDK;
        [nodesArray addObject:midNode];
        
        
        [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Highway naviNodes:nodesArray time:nil delegete:self userInfo:nil];
    }
    
   
}

- (BOOL)checkServicesInited
{
    if(![BNCoreServices_Instance isServicesInited])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"引擎尚未初始化完成，请稍后再试"
                                                           delegate:nil
                                                  cancelButtonTitle:@"我知道了"
                                                  otherButtonTitles:nil];
        [alertView show];
        return NO;
    }
    return YES;
}

//- (void)recordTrackingWithUserLocation:(BMKUserLocation *)userLocation
//{
//    if (self.preLocation) {
//        // 计算本次定位数据与上次定位数据之间的距离
//        CGFloat distance = [userLocation.location distanceFromLocation:self.preLocation];
//        self.statusView.distanceWithPreLoc.text = [NSString stringWithFormat:@"%.3f",distance];
//        NSLog(@"与上一位置点的距离为:%f",distance);
//        // (5米门限值，存储数组画线) 如果距离少于 5 米，则忽略本次数据直接返回方法
//        if (distance < 5) {
//            return;
//        }
//    }
//    // 2. 将符合的位置点存储到数组中（第一直接来到这里）
//    [self.locationArrayM addObject:userLocation.location];
//    self.preLocation = userLocation.location;
//    // 3. 绘图
//    [self drawWalkPolyline];
//}
//
//- (void)drawWalkPolyline
//{
//    // 轨迹点数组个数
//    NSUInteger count = self.locationArrayM.count;
//    // 动态分配存储空间
//    // BMKMapPoint是个结构体：地理坐标点，用直角地理坐标表示 X：横坐标 Y：纵坐标
//    BMKMapPoint *tempPoints = new BMKMapPoint[count];
//    // 遍历数组
//    [self.locationArrayM enumerateObjectsUsingBlock:^(CLLocation *location, NSUInteger idx, BOOL *stop) {
//        BMKMapPoint locationPoint = BMKMapPointForCoordinate(location.coordinate);
//        tempPoints[idx] = locationPoint;
//    }
//     }];
//    //移除原有的绘图，避免在原来轨迹上重画
//    if (self.polyLine) {
//        [self.mapView removeOverlay:self.polyLine];
//    }
//    // 通过points构建BMKPolyline
//    self.polyLine = [BMKPolyline polylineWithPoints:tempPoints count:count];
//    //添加路线,绘图
//    if (self.polyLine) {
//        [self.mapView addOverlay:self.polyLine];
//    }
//    // 清空 tempPoints 临时数组
//    delete []tempPoints;
//    // 根据polyline设置地图范围
//    [self mapViewFitPolyLine:self.polyLine];
//}

//导航按钮事件
#pragma mark - GSMapNavViewDelegate

- (void)navViewDidTapZoomInBtn:(GSMapNavView *)view
{
    [self.mapView zoomIn];
}

- (void)navViewDidTapZoomOutBtn:(GSMapNavView *)view
{
    [self.mapView zoomOut];
}


//显示我当前的位置
- (void)navViewDidTapNavBtn:(GSMapNavView *)view
{
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    
    //根据用户当前位置（[[GSMapManager shareManager] userLocation]），更新地图
    [_mapView updateLocationData:[[GSMapManager shareManager] userLocation]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        _mapView.zoomLevel = kMapViewDefaultZoomLevel;
    });
    
    
    [[GSMapManager shareManager] startLocateMyLocation];
}

#pragma mark - BMKMapViewDelegate

//地图加载完的回调
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
   //Do nothing
}

//当地图上添加了Annotation 数据，代理负责组装一个视图，用于在地图上显示
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    BMAnnotationView *annotationView = nil;   //视图
    static NSString *annotationViewIdentifier = @"annotationViewIdentifier";
    
    //数据转换
    BMPointAnnotation *bmAnnotation = (BMPointAnnotation *)annotation;
    
    if ([bmAnnotation isKindOfClass:[BMPointAnnotation class]])
    {
        //地图会查询当前是否有可被重用的AnnotationView ，有的话就重用，没有则重新分配内存生成一个新的AnnotationView
        annotationView = (BMAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewIdentifier];
        
        //真值的反
        
        if (!annotationView)
        {
            
            //没有可重用的AnnotationView ，重新分配一个新的视图。
            annotationView = [[BMAnnotationView alloc] initWithAnnotation:bmAnnotation reuseIdentifier:annotationViewIdentifier avatarUrl:bmAnnotation.userInfo.avatarUrl];
            
            //配置annotationView 大小
            annotationView.frame = CGRectMake(0, 0, 30, 30);
            
            annotationView.canShowCallout = YES;
        }
        else
        {
            
            //视图被重用，需要重新配置视图内的信息
            [annotationView configureWithAnnotation:bmAnnotation];
        }
        annotationView.delegate = self;
    }
    
    return annotationView;
}

#pragma mark  - BMAnnotationViewDelegate

- (void)didTapNavButton:(CLLocationCoordinate2D)location
{
    [self startRouteTo:location];
}


#pragma mark - BNNaviRoutePlanDelegate
//算路成功回调
-(void)routePlanDidFinished:(NSDictionary *)userInfo
{
    NSLog(@"算路成功");
    //路径规划成功，开始导航
    
    [BNCoreServices_UI showNaviUI:BN_NaviTypeReal delegete:self isNeedLandscape:NO];

}

//算路失败回调
- (void)routePlanDidFailedWithError:(NSError *)error andUserInfo:(NSDictionary *)userInfo
{
    NSLog(@"算路失败");
    if ([error code] == BNRoutePlanError_LocationFailed) {
        NSLog(@"获取地理位置失败");
    }
    else if ([error code] == BNRoutePlanError_LocationServiceClosed)
    {
        NSLog(@"定位服务未开启");
    }
}

//算路取消回调
-(void)routePlanDidUserCanceled:(NSDictionary*)userInfo {
    NSLog(@"算路取消");
}

#pragma mark - BNNaviUIManagerDelegate

//退出导航回调
-(void)onExitNaviUI:(NSDictionary*)extraInfo
{
    NSLog(@"退出导航");
}

//退出导航声明页面回调
- (void)onExitDeclarationUI:(NSDictionary*)extraInfo
{
    NSLog(@"退出导航声明页面");
}

-(void)onExitDigitDogUI:(NSDictionary*)extraInfo
{
    NSLog(@"退出电子狗页面");
}


#pragma mark - GSMapBottomBarDelegate

- (void)didSelectButtonIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
        {
            if ([[BMUserManager shareManager] isLogin])
            {
                [GSToast showProgressToastInView:self.view];
                [self.mapView removeAnnotations:self.mapView.annotations];
                
                [[BMUserManager shareManager] fetchFriendsListWithCompletedBlock:^(NSArray<BMUserInfo *> *list) {
                    
                    [GSToast hideProgressToastInView:self.view];
                    
                    
                    //遍历朋友列表，配置annotation
                    [list enumerateObjectsUsingBlock:^(BMUserInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        BMPointAnnotation *annotation = [[BMPointAnnotation alloc] initWithCoordinate:obj.coordinate userInfo:obj];
                        
                        //地图上添加了Annotation ，则viewForAnnotation 会被调用
                        [self.mapView addAnnotation:annotation];
                    }];
                    
                }];
            }
            else
            {
                [UIAlertView bk_showAlertViewWithTitle:@"" message:@"完善个人资料才能查看朋友列表哦！亲" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1)
                    {
                        [self performSegueWithIdentifier:@"BMUserInfoviewController" sender:nil];
                    }
                }];
            }
            
        }
            break;
        case 1:
        {
            [self performSegueWithIdentifier:@"BMUserInfoviewController" sender:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark - Getter && Setter

- (BMKMapView *)mapView
{
    if(!_mapView)
    {
        _mapView                   = [[BMKMapView alloc] initWithFrame:self.view.bounds];
        _mapView.zoomLevel         = kMapViewDefaultZoomLevel;
        _mapView.minZoomLevel      = 5;
        _mapView.maxZoomLevel      = 20;
        _mapView.showsUserLocation = NO;
        _mapView.userTrackingMode  = BMKUserTrackingModeFollow;
        _mapView.showsUserLocation = YES;
        _mapView.delegate          = self;
        _mapView.logoPosition      = BMKLogoPositionLeftBottom;
        
        BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
        param.locationViewImgName          = @"icon_home_location3";
        param.isAccuracyCircleShow = NO;
        [_mapView updateLocationViewWithParam:param];
    }
    
    return _mapView;
}

- (GSMapNavView *)navView
{
    if (!_navView)
    {
        _navView = [[GSMapNavView alloc] initWithDelegate:self];
    }
    return _navView;
}

- (GSMapBottomBar *)bottomBar
{
    if (!_bottomBar)
    {
        NSMutableArray *buttonsInfos = [NSMutableArray array];
        NSArray *images = @[@"icon_home_my",@"icon_home_my"];
        NSArray *titles = @[@"查看朋友位置",@"我的"];
        
        for (int i = 0; i < images.count; i++)
        {
            NSString *imageName      = [images objectAtIndex:i];
            NSString *title          = [titles objectAtIndex:i];
            GSBottomButtonInfo *info = [[GSBottomButtonInfo alloc] initWithTitle:title image:[UIImage imageNamed:imageName]];
            [buttonsInfos addObject:info];
        }
        _bottomBar = [[GSMapBottomBar alloc] initWithButtons:buttonsInfos delegate:self];
    }
    return _bottomBar;
}
@end
